package cn.tradewin.pmp.services.impl;

import java.util.List;

import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;

import cn.tradewin.pmp.persist.client.MPositionMapper;
import cn.tradewin.pmp.persist.model.MPosition;
import cn.tradewin.pmp.services.PositionManageService;

public class PositionManageServiceImpl implements PositionManageService {

	private final SqlSessionFactory sqlSessionFactory;
	
	public PositionManageServiceImpl(SqlSessionFactory sqlSessionFactory) {
		this.sqlSessionFactory = sqlSessionFactory;
	}
	
	@Override
	public int AddPosition(MPosition position) {
		SqlSession session = null;
		try {
			session = sqlSessionFactory.openSession();
			MPositionMapper mapper = session.getMapper(MPositionMapper.class);
			int iCount = mapper.insert(position);
			if (iCount > 0) {
				session.commit();
			}
			return iCount;
		} catch (Exception e) {
			session.rollback();
			throw new RuntimeException(e.getMessage());
		}
	}

	@Override
	public int updPosition(MPosition position) {
		SqlSession session = null;
		try {
			session = sqlSessionFactory.openSession();
			MPositionMapper mapper = session.getMapper(MPositionMapper.class);
			int iCount = mapper.updateByPrimaryKey(position);
			if (iCount > 0) {
				session.commit();
			}
			return iCount;
		} catch (Exception e) {
			session.rollback();
			throw new RuntimeException(e.getMessage());
		}
	}

	@Override
	public int DelPositions(List<Integer> positions) {
		SqlSession session = null;
		try {
			session = sqlSessionFactory.openSession();
			MPositionMapper mapper = session.getMapper(MPositionMapper.class);
			int iDels = mapper.deleteByPrimaryKeyList(positions);
			if (iDels > 0) {
				session.commit();
			}
			return iDels;
		} catch (Exception e) {
			throw new RuntimeException(e.getMessage());
		}
	}

	@Override
	public List<MPosition> getAllPositions() {
		SqlSession session = null;
		try {
			session = sqlSessionFactory.openSession();
			MPositionMapper mapper = session.getMapper(MPositionMapper.class);
			return mapper.selectByExample(null);
		} catch (Exception e) {
			session.rollback();
			throw new RuntimeException(e.getMessage());
		}
	}

	@Override
	public MPosition findPositionByPrimary(Integer positionNo) {
		SqlSession session = null;
		try {
			session = sqlSessionFactory.openSession();
			MPositionMapper mapper = session.getMapper(MPositionMapper.class);
			return mapper.selectByPrimaryKey(positionNo);
		} catch (Exception e) {
			session.rollback();
			throw new RuntimeException(e.getMessage());
		}
	}

}
